package com.thekernel.youdaoyun.service.impl;

import com.thekernel.youdaoyun.bean.User;
import com.thekernel.youdaoyun.exception.MyException;
import com.thekernel.youdaoyun.exception.impl.DataNotFoundException;
import com.thekernel.youdaoyun.exception.impl.IllegalUserException;
import com.thekernel.youdaoyun.exception.impl.PasswordNotSameException;
import com.thekernel.youdaoyun.exception.impl.UserNotLoginException;
import com.thekernel.youdaoyun.mapper.UserMapper;
import com.thekernel.youdaoyun.service.UserService;
import com.thekernel.youdaoyun.util.FileUtils;
import com.thekernel.youdaoyun.util.PasswordUtils;
import com.thekernel.youdaoyun.util.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Field;
import java.util.Date;

/**
 * @Author TheKernel
 * @Date 2019/9/12 7:17 下午
 * @Version 1.0
 * @Description UserService 的具体实现
 */
@Service("UserService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 注册用户
     *
     * @param user 用户信息(username, password, user_type 必需)
     * @return -1: Data Not Found, 0: Username Already Exist, 1: Success
     */
    @Override
    public int register(User user) {
        // 检测数据是否完全
        if (user.getUsername() == null || user.getPassword() == null) {
            return -1;
        }
        // 检测数据库中是否已存在该用户
        User dbUser = this.userMapper.queryUserIdByUsername(user.getUsername());
        if (dbUser != null) {
            return 0;
        }
        // 用户默认属性
        if (user.getUserType() == null) {
            user.setUserType(1);
        }
        user.setPassword(PasswordUtils.encrypt(user.getPassword()));
        user.setStatus(Boolean.TRUE);
        user.setCreateTime(new Date());

        return this.userMapper.add(user);
    }

    /**
     * 用户登录
     *
     * @param user 用户信息(username, password)
     * @return 用户type / -1: Data Not Found, 0: Username/password Error
     */
    @Override
    public User login(User user) throws MyException {
        // 检测数据是否完全
        if (user.getUsername() == null || user.getPassword() == null) {
            throw new DataNotFoundException();
        }
        // 检测用户是否存在以及密码是否正确
        User dbUser = this.userMapper.queryPasswordByUsername(user.getUsername());
        String password = PasswordUtils.encrypt(user.getPassword());
        if (dbUser == null || !dbUser.getPassword().equals(password)) {
            throw new PasswordNotSameException();
        }

        return dbUser;
    }

    /**
     * 修改用户信息
     *
     * @param user 修改后的用户信息
     * @return 1: 修改成功 0: 修改失败
     * @throws MyException 非本人操作等
     */
    @Override
    public int update(User user) throws MyException {
        if (user.getUserId() == 0) {
            user.setUserId(UserUtils.checkReturnUserId());
        } else {
            if (user.getUserId() != UserUtils.checkReturnUserId()) {
                throw new IllegalUserException();
            }
        }
        User dbUser = this.userMapper.queryUserByUserId(user.getUserId());
        combineSydwCore(user, dbUser);

        return this.userMapper.updateUser(dbUser);
    }

    /**
     * 成为会员
     *
     * @param user 修改后的用户信息
     * @return 1: 修改成功 0: 修改失败
     * @throws MyException 非本人操作等
     */
    @Override
    public int becomeViper(User user) throws MyException {
        if (user.getUserId() == 0) {
            user.setUserId(UserUtils.checkReturnUserId());
        } else {
            if (user.getUserId() != UserUtils.checkReturnUserId()) {
                throw new IllegalUserException();
            }
        }

        return this.userMapper.becomeVip(user.getUserId());
    }

    /**
     * 查看用户个人资料
     *
     * @return 用户信息
     * @throws MyException 权限不足等
     */
    @Override
    public User viewSelf() throws MyException {
        long userId = UserUtils.checkReturnUserId();
        return this.userMapper.queryUserByUserId(userId);
    }


    /**
     * 更新用户头像
     *
     * @param avatar 用户头像
     * @return 1: 更新成功 0: 更新失败
     * @throws UserNotLoginException 用户未登录异常
     */
    @Override
    public int updateAvatar(MultipartFile avatar) throws UserNotLoginException {
        long userId = UserUtils.checkReturnUserId();
        String avatarName = FileUtils.uploadAvatar(avatar);

        return this.userMapper.updateAvatar(userId, avatarName);
    }

    /**
     * 修改密码
     *
     * @param user 用户
     * @return 1: 修改成功 -1: 修改失败
     * @throws MyException 用户未登录异常
     */
    @Override
    public int updatePassword(User user) throws MyException {
        if (user.getPassword().equals("") || user.getUserId() == 0) {
            return -1;
        }
        return this.userMapper.updatePassword(user);
    }

    private void combineSydwCore(Object sourceBean, Object targetBean) {
        Class sourceBeanClass = sourceBean.getClass();
        Class targetBeanClass = targetBean.getClass();

        Field[] sourceFields = sourceBeanClass.getDeclaredFields();
        Field[] targetFields = sourceBeanClass.getDeclaredFields();
        for (int i = 1; i < sourceFields.length; i++) {
            Field sourceField = sourceFields[i];
            Field targetField = targetFields[i];
            sourceField.setAccessible(true);
            targetField.setAccessible(true);
            try {
                if (sourceField.get(sourceBean) != null) {
                    System.out.println(sourceField.get(sourceBean));
                    targetField.set(targetBean, sourceField.get(sourceBean));
                }
            } catch (IllegalArgumentException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

}
